package cn.glutnn.service.impl;

import cn.glutnn.entity.AdminUser;
import cn.glutnn.entity.Result;
import cn.glutnn.entity.dto.LoginDTO;
import cn.glutnn.mapper.AdminUserMapper;
import cn.glutnn.service.AdminUserService;
import cn.glutnn.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员用户服务实现类
 * @author msh
 * @date 2025/04/04
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Override
    public Result login(LoginDTO loginDTO) {
        try {
            // 认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取管理员用户信息
            AdminUser adminUser = findByUsername(loginDTO.getUsername());
            
            // 更新最后登录时间
            adminUser.setLastLoginTime(LocalDateTime.now());
            updateById(adminUser);
            
            // 生成token
            String token = jwtUtil.generateToken(adminUser.getUsername(), adminUser.getId());
            
            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("userInfo", adminUser);
            
            return Result.success("登录成功", result);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
    }
    
    @Override
    public AdminUser findByUsername(String username) {
        return baseMapper.findByUsername(username);
    }
    
    @Override
    public Page<AdminUser> page(Page<AdminUser> page, String username, String role, Integer status) {
        LambdaQueryWrapper<AdminUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(username), AdminUser::getUsername, username)
                .eq(StringUtils.hasText(role), AdminUser::getRole, role)
                .eq(status != null, AdminUser::getStatus, status)
                .orderByDesc(AdminUser::getCreateTime);
        
        return page(page, wrapper);
    }
    
    @Override
    public Result create(AdminUser adminUser) {
        // 检查用户名是否已存在
        AdminUser existingUser = findByUsername(adminUser.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        
        // 设置默认值
        adminUser.setPassword(passwordEncoder.encode(adminUser.getPassword()));
        adminUser.setCreateTime(LocalDateTime.now());
        adminUser.setUpdateTime(LocalDateTime.now());
        adminUser.setIsDeleted(0);
        
        // 保存管理员用户
        save(adminUser);
        
        return Result.success("创建成功", adminUser);
    }
    
    @Override
    public Result update(AdminUser adminUser) {
        // 获取原始数据
        AdminUser originalUser = getById(adminUser.getId());
        if (originalUser == null) {
            return Result.error("用户不存在");
        }
        
        // 如果修改了用户名，检查是否已存在
        if (!originalUser.getUsername().equals(adminUser.getUsername())) {
            AdminUser existingUser = findByUsername(adminUser.getUsername());
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }
        }
        
        // 如果密码不为空，则加密
        if (StringUtils.hasText(adminUser.getPassword())) {
            adminUser.setPassword(passwordEncoder.encode(adminUser.getPassword()));
        } else {
            adminUser.setPassword(originalUser.getPassword());
        }
        
        // 设置更新时间
        adminUser.setUpdateTime(LocalDateTime.now());
        
        // 更新管理员用户
        updateById(adminUser);
        
        return Result.success("更新成功");
    }
    
    @Override
    public Result delete(Integer id) {
        // 检查用户是否存在
        AdminUser adminUser = getById(id);
        if (adminUser == null) {
            return Result.error("用户不存在");
        }
        
        // 不允许删除超级管理员
        if ("ADMIN".equals(adminUser.getRole())) {
            return Result.error("不允许删除超级管理员");
        }
        
        // 逻辑删除
        removeById(id);
        
        return Result.success("删除成功");
    }
    
    @Override
    public Result updateStatus(Integer id, Integer status) {
        // 检查用户是否存在
        AdminUser adminUser = getById(id);
        if (adminUser == null) {
            return Result.error("用户不存在");
        }
        
        // 不允许禁用超级管理员
        if ("ADMIN".equals(adminUser.getRole()) && status == 0) {
            return Result.error("不允许禁用超级管理员");
        }
        
        // 更新状态
        adminUser.setStatus(status);
        adminUser.setUpdateTime(LocalDateTime.now());
        updateById(adminUser);
        
        return Result.success("更新成功");
    }
} 